﻿using AutoMapper;
using Basic.Traceability.Domain.DeepProcessing;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.DeepProcessing.DeepProcessingRawMaterial;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;
using Yitter.IdGenerator;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.DeepProcessing.DeepProcessingRawMaterial
{
    public class CreateDeepProcessingRawMaterialHandler : IRequestHandler<CreateDeepProcessingRawMaterialCommand, APIResult<int>>
    {
        private readonly IBaseRepository<DeepProcessingRawMaterialModel> _deepProcessingRawMaterialRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateDeepProcessingRawMaterialHandler> _logger;

        public CreateDeepProcessingRawMaterialHandler(IBaseRepository<DeepProcessingRawMaterialModel> deepProcessingRawMaterialRepository, IMapper mapper, ILogger<CreateDeepProcessingRawMaterialHandler> logger)
        {
            _deepProcessingRawMaterialRepository = deepProcessingRawMaterialRepository;
            _mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 添加深加工原料信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateDeepProcessingRawMaterialCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = _mapper.Map<DeepProcessingRawMaterialModel>(request);
            model.Id = YitIdHelper.NextId();
            var r = _deepProcessingRawMaterialRepository.Create(model);
            if (r > 0)
            {
                res.Msg = "添加深加工原料信息成功";
                res.Data = r;
                res.Code = APIEnums.Success;
                _logger.LogInformation("添加深加工原料信息成功");
                return Task.FromResult(res);

            }
            else
            {
                res.Msg = "添加深加工原料信息失败";
                res.Code = APIEnums.Fail;
                res.Data = r;
                _logger.LogError("添加深加工原料信息失败");
                return Task.FromResult(res);
            }

        }
    }
}
